﻿namespace com.game.basic.events
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using UnityEngine;
    using UnityEngine.Events;

    public class EasyEventDispatcher
    {
        private Dictionary<string, EventArg> eventDic = new Dictionary<string, EventArg>();

        public void AddEventListener(string type, UnityAction<EventArg> listener)
        {
            if (this.eventDic.ContainsKey(type))
            {
                this.eventDic[type].AddListener(listener);
            }
            else
            {
                this.eventDic.Add(type, new EventArg(type));
                this.eventDic[type].AddListener(listener);
            }
        }

        public void Dispatcher(EventArg arg)
        {
            if (this.eventDic.ContainsKey(arg.eventType))
            {
                this.eventDic[arg.eventType].notifier = this;
                this.eventDic[arg.eventType].Invoke(arg);
            }
            else
            {
                Debug.LogError("Event:" + arg.eventType + " has never been registered");
            }
        }

        public void Dispatcher(string type, object arg = null)
        {
            this.Dispatcher(new EventArg(type, arg));
        }

        public bool HasEventListener(string type)
        {
            return this.eventDic.ContainsKey(type);
        }

        public void RemoveEventListener(string type, UnityAction<EventArg> call)
        {
            if (this.eventDic.ContainsKey(type))
            {
                this.eventDic[type].RemoveListener(call);
            }
        }
    }
}

